import React, { PureComponent } from 'react';
import { DATA_ENTRY, AdvancedSearch, ContentPackage, NoDataC, PrimaryC } from '../../../components';
import { Modal, Pagination, Spin, message } from 'antd';
import CardC from './CardC';
import { connect } from 'dva';
import myStyle from './style.less';
import AddModalC from './AddModalC';
import config from '../../../utils/enumeratedValues/workStationModuleEnum';

class TableListC extends PureComponent {
  state = {
    dataSource: undefined,
    total: undefined,
    currentPage: 1,
    numInPage: 9,
    searchValue: {}, // 查询条件
    isReset: false, // 是否点击了重置
    isVisible: false, // 是否显示弹窗
    currentData: {}, // 当前编辑数据
    menuList: [], // 菜单下拉列表
    fullTenants: [], // 租户列表
  };

  componentDidMount() {
    this.queryMenuList(); // 查询菜单下拉列表
    this.queryTenantList(); // 查询租户列表
    this.queryData(); // 查询列表
  }

  // 查询菜单列表
  queryMenuList = () => {
    this.props.dispatch({
      type: 'systemNoticeSettingM/queryMenuList',
      payload: { userId: localStorage.getItem('antd-pro-userId') },
      callback: (data) => {
        if (data) {
          const arr = [...config, ...data];
          arr.map((item) => {
            this.changeMenuList(item);
          });
          arr.map((item) => {
            if (item.name == '其它') {
              item.value = 'OperatePlatform1';
            }
          });
          this.setState({
            menuList: arr,
          });
        }
      },
    });
  };

  // 查询租户列表
  queryTenantList = () => {
    this.props.dispatch({
      type: 'tenantM/getTenantList',
      payload: {},
      callback: (data) => {
        this.setState({
          fullTenants: [...data],
        });
      },
    });
  };

  // 将菜单变成value title树形格式
  changeMenuList = (item) => {
    if (item.menuModels && item.menuModels.length) {
      item.value = item.value ? item.value : item.path;
      item.title = item.name;
      item.pageName = item.pageName ? item.pageName : item.name;
      item.selectable = false;
      item.menuModels.map((x) => {
        x.pageName = `${item.pageName}/${x.name}`;
        x.title = x.name;
        x.value = x.menuModels && item.menuModels.length ? `${item.value}/${x.path}` : `/${item.value}/${x.path}`;
        if (x.menuModels && item.menuModels.length) this.changeMenuList(x);
      });
      item.children = item.menuModels;
    } else {
      item.value = item.value ? item.value : `/${item.path}`;
      item.title = item.name;
      item.pageName = item.pageName ? item.pageName : item.name;
    }
  };

  // 查询
  queryData = () => {
    const { searchValue } = this.state;
    if (searchValue.startDate && searchValue.startDate != '') searchValue.startDate = searchValue.startDate.format('YYYY-MM-DD');
    if (searchValue.endDate && searchValue.endDate != '') searchValue.endDate = searchValue.endDate.format('YYYY-MM-DD');
    this.props.dispatch({
      type: 'systemNoticeSettingM/queryTableList',
      payload: {
        ...searchValue,
        currentPage: this.state.currentPage,
        numInPage: this.state.numInPage,
        history: '2', // 1提醒2公告设置
      },
      callback: (data) => {
        if (data) {
          this.setState({
            dataSource: data.dataSource || [],
            total: data?.pageInfo?.total || undefined,
          });
        } else {
          this.setState({
            dataSource: [],
            total: undefined,
          });
        }
      },
    });
  };

  // 每页条数变化
  onShowSizeChange = (current, pageSize) => {
    if (this.state.isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryData();
      },
    );
  };

  // 页码变化
  handlePageChange = (current, pageSize) => {
    if (this.state.isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryData();
      },
    );
  };

  // 新增报告
  addNotice = () => {
    this.onRefresh();
    this.setState({
      isVisible: true,
    });
  };

  // 编辑报告
  editData = (data) => {
    this.queryData();
    this.setState({
      currentData: data,
      isVisible: true,
    });
  };

  // 删除报告
  deleteData = (data) => {
    Modal.confirm({
      title: '确定删除吗?',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: 'systemNoticeSettingM/deleteNotice',
          payload: {
            id: data?.id,
          },
          callback: () => {
            this.onRefresh();
          },
        });
      },
    });
  };

  // 新增成功 刷新页面
  onOK = () => {
    this.onRefresh();
    this.setState({
      isVisible: false,
      currentData: {},
    });
  };

  // 取消关闭页面
  onCancel = () => {
    this.setState({
      isVisible: false,
      currentData: {},
    });
  };

  // 刷新
  onRefresh = () => {
    this.searchRef.handleReset();
    this.setState(
      {
        searchValue: {},
        currentPage: 1,
      },
      () => {
        this.queryData();
      },
    );
  };

  render() {
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['startDate', 'endDate'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          allowClear: true,
          disableFuture: false,
        },
        {
          dataIndex: 'title',
          title: '标题',
          type: DATA_ENTRY.INPUT,
        },
      ],
      onRef: (ref) => {
        this.searchRef = ref;
      },
      // 点击查询按钮
      onQuery: (e) => {
        this.setState(
          {
            searchValue: e || {},
            isReset: false,
            currentPage: 1,
          },
          () => {
            this.queryData();
          },
        );
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          searchValue: {},
          isReset: true,
        });
      },
    };
    const { dataSource, total, currentPage, numInPage } = this.state;
    return (
      <ContentPackage
        title={this.props.type == '2' ? '历史公告查询' : '系统公告设置'}
        contentHtml={
          <>
            <div style={{ margin: '0 0 20px 0px' }}>
              <AdvancedSearch {...searchProps} />
            </div>
            {this.props.type == '1' && <PrimaryC title='新增' onClick={this.addNotice} style={{ marginBottom: '20px' }} />}
            <Spin spinning={this.props.loading.effects['systemNoticeSettingM/queryTableList'] == true}>
              {dataSource && dataSource.length ? (
                <div className={myStyle.tableList}>
                  <div className={myStyle.cardItem}>
                    {dataSource &&
                      dataSource.map((item, key) => {
                        item.isWarning = item.remindTenants ? item.remindTenants.length : false;
                        return (
                          <div key={key} style={{ marginBottom: '20px' }}>
                            <CardC itemData={item} editData={this.editData} deleteData={this.deleteData} fullTenants={this.state.fullTenants} type={this.props.type} />
                          </div>
                        );
                      })}
                  </div>

                  <div style={{ float: 'right', marginTop: '20px' }}>
                    <Pagination
                      showQuickJumper={true}
                      showSizeChanger={true}
                      onShowSizeChange={this.onShowSizeChange}
                      total={total}
                      showTotal={(total) => `共计 ${total} 条`}
                      pageSize={numInPage}
                      current={currentPage}
                      onChange={this.handlePageChange}
                      pageSizeOptions={['9', '27', '45']}
                    />
                  </div>
                </div>
              ) : (
                <NoDataC />
              )}
            </Spin>
            {this.state.isVisible && (
              <AddModalC detailData={this.state.currentData} onOk={this.onOK} onCancel={this.onCancel} visible={this.state.isVisible} menuList={this.state.menuList} />
            )}
          </>
        }
      />
    );
  }
}
export default connect(({ systemNoticeSettingM, tenantM, userM: user, loading }) => ({
  systemNoticeSettingM,
  tenantM,
  user,
  loading,
}))(TableListC);
